package com.nus.servlets;

import com.nus.beans.User;
import com.nus.beans.UserSubType;
import com.nus.beans.UserType;
import com.nus.database.UserDBManager;
import com.nus.services.ConversionService;
import com.nus.services.EncodingService;
import com.nus.services.ValidationService;
import org.apache.log4j.Logger;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.util.Date;

/**
 * Created by IntelliJ IDEA.
 * User: dell
 * Date: 9/23/12
 * Time: 7:41 PM
 * To change this template use File | Settings | File Templates.
 */
public class CreateUserServlet extends AbstractServlet {
    private Logger logger = Logger.getLogger(this.getClass());

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String loginName = request.getParameter("loginName");
        String password1 = request.getParameter("password1");
        String password2 = request.getParameter("password2");
        String userType = request.getParameter("userType");
        String userSubType = request.getParameter("userSubType");
        String firstName = request.getParameter("firstName");
        String familyName = request.getParameter("familyName");
        String yearFrom = request.getParameter("yearFrom");
        String monthFrom = request.getParameter("monthFrom");
        String dayFrom = request.getParameter("dayFrom");
        String address1 = request.getParameter("address1");
        String phoneNo = request.getParameter("phoneNo");
        String salary = request.getParameter("Salary");
        String leaves = request.getParameter("leaves");

        ValidationService validationService = new ValidationService();
        ConversionService conversionService = new ConversionService();
        String errorMessage;

        String nextPage = "/WEB-INF/create_user.jsp";
        RequestDispatcher requestDispatcher = request.getRequestDispatcher(nextPage);
        String encodedPassword;

        if (validationService.isEmpty(loginName)) {
            errorMessage = "login name should not be empty";
            logger.error(errorMessage);
        } else if (validationService.isEmpty(password1)) {
            errorMessage = "password should not be empty";
            logger.error(errorMessage);
        } else if (validationService.isEmpty(password2)) {
            errorMessage = "password2 should not be empty";
            logger.error(errorMessage);
        } else if (!password1.equals(password2)) {
            errorMessage = "Both passwords should be the same.";
            logger.error(errorMessage);
        } else if (validationService.isEmpty(userType)) {
            errorMessage = "User type should not be empty";
            logger.error(errorMessage);
        } else if (validationService.isEmpty(familyName)) {
            errorMessage = "Family name should not be empty";
            logger.error(errorMessage);
        } else if (validationService.isEmpty(yearFrom) || validationService.isEmpty(monthFrom) || validationService.isEmpty(dayFrom)) {
            errorMessage = "Date of birth should not be empty";
            logger.error(errorMessage);
        } else if (validationService.isEmpty(phoneNo)) {
            errorMessage = "Phone number should not be empty";
            logger.error(errorMessage);
        } else if (validationService.isEmpty(salary)) {
            errorMessage = "Salary should not be empty";
            logger.error(errorMessage);
        } else if (validationService.isEmpty(leaves)) {
            errorMessage = "Leaves should not be empty";
            logger.error(errorMessage);
        } else if (validationService.isEmpty(address1)) {
            errorMessage = "Address should not be empty";
            logger.error(errorMessage);
        } else if (!validationService.isNumber(salary)) {
            errorMessage = "Salary must be a number";
        } else if (!validationService.isNumber(phoneNo)) {
            errorMessage = "Phone number must be a number";
        } else if (!validationService.isNumber(leaves)) {
            errorMessage = "Remaining leaves be a number";
        } else if(!(userSubType.equals(UserSubType.NONE.toString()) ^ userType.equals(UserType.DEVELOPER.toString()))){
            errorMessage = "For developer user type sub type is mandatory and for other users user sub type is not defined.";
        } else {
            Date date = conversionService.getDate(yearFrom, monthFrom, dayFrom);
            if (date == null) {
                errorMessage = "Invalid date for date of birth.";
            } else if (date.after(new Date())) {
                errorMessage = "Date of birth should be before the current date";
            } else if(!validationService.isGreaterThanZero(salary)){
                errorMessage = "Negative values not allowed for salary.";
            } else if(!validationService.isGreaterThanZero(leaves)) {
                errorMessage = "Negative values not allowed for remaining leaves.";
            } else {

                User user = new User();
                user.setFirstName(firstName);

                EncodingService encodingService = new EncodingService();
                encodedPassword = encodingService.encode(password1);
                user.setPassword(encodedPassword);
                user.setBasicSalary(Integer.parseInt(salary));

                user.setDateOfBirth(date);
                user.setLastName(familyName);
                user.setLoginName(loginName.toUpperCase());
                user.setPhoneNumber(Long.parseLong(phoneNo));
                user.setRemainingLeaves(Integer.parseInt(leaves));
                user.setUserType(UserType.valueOf(userType));
                user.setAddress(address1);
                user.setUserSubType(UserSubType.valueOf(userSubType.toUpperCase()));

                Connection connection = getUserDatabaseConnection(request);
                UserDBManager userDBManager = new UserDBManager(connection);

                boolean isValidLogin = userDBManager.validateLoginName(user.getLoginName());
                if (!isValidLogin) {
                    errorMessage = "Login name is already used. Please try again with a different login name";
                } else {
                    userDBManager.createUser(user);
                    errorMessage = "User successfully created";
                }

                userDBManager.close();
            }
        }

        request.setAttribute("ERROR_MESSAGE", errorMessage);
        requestDispatcher.forward(request, response);
    }
}
